package edu.ucsd.cse110;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import edu.ucsd.cse110.model.Log;
import edu.ucsd.cse110.model.Wod;

/**
 * Displays all the log entries at a specific day.
 */
public class MultipleLogActivity extends ListActivity {
	private List<Log> mList;

	/**
	 * TODO: Need documentation.
	 * 
	 * @param entry
	 * @return
	 */
	private String getWodName(int entry) {
		LocalDatabaseManager db = new LocalDatabaseManager(this);

		String result = "";
		Wod d;
		Log l = mList.get(entry);

		if (l.getWodId() != 0) {
			d = db.getWodById(l.getWodId()).get(0);
			result = d.getName();
		} else {
			result = "None";
		}

		db.close();

		return result;
	}

	/**
	 * TODO: Need documentation.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.multiple_logs);

		Bundle bundle = getIntent().getExtras();

		Calendar c = Calendar.getInstance();
		c.clear();
		c.set(Calendar.YEAR, bundle.getInt("year"));
		c.set(Calendar.MONTH, bundle.getInt("month"));
		c.set(Calendar.DATE, bundle.getInt("day"));

		LocalDatabaseManager db = new LocalDatabaseManager(this);
		mList = db.getLog(String.format("%s = ?", Log.COLUMNS[1]),
				new String[] { Long.toString(c.getTimeInMillis()) }, null,
				null, null);
		db.close();

		List<String> stringList = new ArrayList<String>();

		for (int k = 1; k <= mList.size(); k++) {
			stringList.add(String.format("Entry %d: %s", k, getWodName(k - 1)));
		}

		setListAdapter(new ArrayAdapter<String>(getBaseContext(),
				android.R.layout.simple_list_item_1, stringList));
	}

	/**
	 * TODO: Need documentation.
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Log log = mList.get(position);

		Intent intent = new Intent();
		intent.putExtra("id", log.getId());
		setResult(RESULT_OK, intent);
		finish();
	}
}
